package task

import (
	"encoding/json"
	"litetalk/config"
	"litetalk/connect"
	"litetalk/proto"
	"litetalk/tools"
	"time"

	"github.com/go-redis/redis"
	"github.com/sirupsen/logrus"
)

type PushParams struct {
	ServerId string
	UserId   int
	Msg      []byte
	RoomId   int
}

var RedisClient *redis.Client

func GoRun() {

	redisOpt := tools.RedisOption{
		Address:  config.Conf.Redis.RedisAddress,
		Password: config.Conf.Redis.RedisPassword,
		Db:       config.Conf.Redis.Db,
	}
	RedisClient = tools.GetRedisInstance(redisOpt)
	if pong, err := RedisClient.Ping().Result(); err != nil {
		logrus.Infof("RedisClient Ping Result pong: %s,  err: %s", pong, err)
		return
	}

	go func() {
		var (
			result []string
			err    error
		)

		for {
			result, err = RedisClient.BRPop(time.Second*10, config.QueueName).Result()
			if err != nil {
				continue
			}
			// 0 queueName
			// 1 value
			if len(result) >= 2 {
				Push(result[1])
			}
		}
	}()
}

type UserId struct {
	UserId uint `json:"userid"`
}

func Push(msg string) {
	m := &proto.Msg{}
	if err := json.Unmarshal([]byte(msg), m); err != nil {
		logrus.Errorf(" json.Unmarshal err:%v", err)
		return
	}
	switch m.Op {
	case proto.OpSingleSend:
		connect.Push(m)
	case proto.OpGroupSend:
		connect.PushGroup(m)
	case proto.OpKickUserOnline, proto.OpKickUserOffline, proto.OpChangeAvatarNotify, proto.OpChangeSignInfoNotify:
		id := &UserId{}
		json.Unmarshal(m.Msg, id)
		connect.Broadcast(m, id.UserId)
	case proto.OpGroupChangeMemberNotify:
		t := &proto.IMGroupChangeMemberNotify{}
		json.Unmarshal(m.Msg, t)
		multicast_list := t.CurrentUserIdList
		if t.ChangeType == proto.CID_DEL {
			multicast_list = append(multicast_list, t.ChangeUserIdLIst...)
		}
		connect.Multicast(m, multicast_list)
	default:
	}
}
